using System;
using System.Collections.Generic;
using System.Text;

namespace PersistenceObject.Framework.Expressions
{
    class BetweenExpression : BaseExpression
    {
        public BetweenExpression() { }

        public BetweenExpression(string name, object lvalue, object rvalue)
        {
            this.mIsNotBetween = false;
            this.Name = name;
            this.Value = new object[] { lvalue, rvalue };
        }

        protected override string GetCompareType()
        {
            return " = ";
        }

        public override string GetFilter(IDbDriver dbOperator)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("(");
            sb.Append(this.Name);
            if (this.IsNotBetween)
            {
                sb.Append(" not ");
            }
            sb.Append(" BETWEEN  ");
            string paramName = string.Format("{0}{1}", this.Name, this.GetParamCount());
            if (paramName.LastIndexOf(".") != -1)
            {
                paramName = paramName.Substring(paramName.LastIndexOf(".") + 1);
            }
            sb.Append(dbOperator.GetParameterName(paramName));
            this.param.Add(new FieldValue(paramName, ((object[])this.Value)[0]));
            sb.Append(" And ");
            paramName = string.Format("{0}{1}", this.Name, this.GetParamCount());
            if (paramName.LastIndexOf(".") != -1)
            {
                paramName = paramName.Substring(paramName.LastIndexOf(".") + 1);
            }
            sb.Append(dbOperator.GetParameterName(paramName));
            this.param.Add(new FieldValue(paramName, ((object[])this.Value)[1]));
            sb.Append(" " + this.GetSubString(dbOperator));
            sb.Append(")");
            return sb.ToString();
        }

        private bool mIsNotBetween;
        public bool IsNotBetween
        {
            get
            {
                return this.mIsNotBetween;
            }
            set
            {
                this.mIsNotBetween = value;
            }
        }

        #region Only for SqlServer2005 ServiceBroker
        public override string ServiceBrokerGetFilter(IDbDriver dbOperator)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("(");
            sb.Append(this.Name);
            if (this.IsNotBetween)
            {
                sb.Append(" not ");
            }
            sb.Append(" BETWEEN  ");
            sb.Append(ServiceBroker.Utility.Instance.GetParamValue((object[])this.Value)[0]);
            sb.Append(" And ");
            sb.Append(ServiceBroker.Utility.Instance.GetParamValue((object[])this.Value)[1]);
            sb.Append(" " + this.ServiceBrokerGetSubString(dbOperator));
            sb.Append(")");
            return sb.ToString();
        }
        #endregion

    }
}
